package nix.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class DemoQuery {

	/**
	 * Query
	 */
	@Test
	public void fun1() {
		Configuration conf = new Configuration().configure();
		SessionFactory sessionFactory = conf.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction ts = session.beginTransaction();
		// 增加查询条件
		Query query = session.createQuery("from nix.hibernate.User where id = '1'");
		// 返回单个对象
		User user = (User) query.uniqueResult();
		System.out.println(user);
		
		ts.commit();
		session.close();
		sessionFactory.close();
	}
	
	@Test
	public void fun2() {
		Configuration conf = new Configuration().configure();
		SessionFactory sessionFactory = conf.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction ts = session.beginTransaction();
		// 分页查询（limit）
		Query query = session.createQuery("from nix.hibernate.User");
		// 设置从第几条记录开始
		query.setFirstResult(0);
		// 设置返回条数
		query.setMaxResults(2);
		List<User> userList = query.list();
		System.out.println(userList);

		ts.commit();
		session.close();
		sessionFactory.close();
	}
}
